# -*- coding:utf-8 -*-
__author__ = 'weikai'

import logging
from twisted.internet import defer, reactor
from request_cic.login import *
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.async.client import Stomp
from stompest.async.listener import SubscriptionListener
import json
import settings as se
from threadUtil import threadpool
from add_queue import add
from request_cicc.interface.login import login
from request_cicc.interface.cicc_start import startCicc
from insert_session import get_session
from session import getSession

class Consumer(object):
    QUEUE = se.CHINA_CONTINENT_QUEUE
    ERROR_QUEUE = '/queue/testConsumerError'

    def __init__(self, config=None):
        if config is None:
            config = StompConfig(se.MQHOST)
        self.config = config

    @defer.inlineCallbacks
    def run(self):
        client = Stomp(self.config)
        yield client.connect()
        headers = {
            # client-individual mode is necessary for concurrent processing
            # (requires ActiveMQ >= 5.2)
            StompSpec.ACK_HEADER: StompSpec.ACK_AUTO,
            # the maximal number of messages the broker will let you work on at the same time
            'activemq.prefetchSize': '100',
        }

        client.subscribe(self.QUEUE, headers, listener=SubscriptionListener(self.c_repair, errorDestination=self.ERROR_QUEUE))



    def consume(self, client, frame):
        """
        NOTE: you can return a Deferred here
        """
        data = json.loads(frame.body.decode())
        print('Received frame with data %s' % data)

    def c_repair(self, client, frame):
        data = json.loads(frame.body.decode())
        base64strdt = get_session(['4','5'])
        if len(base64strdt) != 0:
            sessiondt = getSession(base64strdt)
            requestcic = sessiondt['5']
        else:
            requestcic = login()
        threadpool(requestcic,data,startCicc)


if __name__ == '__main__':
    #logging.basicConfig(level=logging.INFO,filename='loggmsg.log')
    logging.basicConfig(level=logging.DEBUG)
    Consumer().run()
    reactor.run()